package com.xing.gulimall.product.service.impl;

import com.xing.gulimall.product.entity.CategoryBrandRelationEntity;
import com.xing.gulimall.product.service.CategoryBrandRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xing.common.utils.PageUtils;
import com.xing.common.utils.Query;

import com.xing.gulimall.product.dao.BrandDao;
import com.xing.gulimall.product.entity.BrandEntity;
import com.xing.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;



@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {


    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;


    /**
     * 处理模糊查询问题
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();

        if (!StringUtils.isEmpty(key)) {
            wrapper.eq("brand_id", key).or().like("name", key);
        }

        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 存在问题：修改品牌和分类的时候，应该把关联表也修改了
     * 修改品牌名称冗余问题
     * @param brand
     */
    @Override
    @Transactional(rollbackFor = Exception.class) //事务处理。因为同时更新两个表
    public void updateDetail(BrandEntity brand) {

        //保证冗余字段的数据一致，-brand表的数据更新也要把中间表的数据更新
        this.updateById(brand);
        if(StringUtils.isNotEmpty(brand.getName())){
            //同步更新其它关联表中的数据
            CategoryBrandRelationEntity categoryBrandRelationEntity = new CategoryBrandRelationEntity();
            categoryBrandRelationEntity.setBrandId(brand.getBrandId());
            categoryBrandRelationEntity.setBrandName(brand.getName());
            categoryBrandRelationService.updateDetail(categoryBrandRelationEntity);
        }

    }

}